package com.tongren.framework.me.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.tongren.framework.R;
import com.tongren.framework.callback.JsonCallback;
import com.tongren.framework.core.BaseListActivity;
import com.tongren.framework.core.CustomApplication;
import com.tongren.framework.model.BasePageModel;
import com.tongren.framework.model.BaseResult;
import com.tongren.framework.model.BaseUser;
import com.tongren.framework.model.BaseWrongBook;
import com.tongren.framework.utils.DateHelper;
import com.tongren.framework.widgets.pull.BaseViewHolder;
import com.tongren.framework.widgets.pull.PullRecycler;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import static com.tongren.framework.constants.ConstantValues.BASE_URL;

/**
 * zhangxu
 */
public class WrongBookListActivity extends BaseListActivity<BaseWrongBook> {

    private int page = 1;
    private boolean isInitCache = false;

    @Override
    protected void setUpTitle(int titleResId) {
        super.setUpTitle(R.string.title_wrong_book);
    }

    @Override
    protected void setUpData(Bundle savedInstanceState) {
        super.setUpData(savedInstanceState);
        recycler.setRefreshing();
    }

    @Override
    protected BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.wrong_book_list_item, parent, false);
        return new SampleViewHolder(view);
    }



    @Override
    public void onRefresh(final int action) {
        if (mDataList == null) {
            mDataList = new ArrayList<>();
        }

        if (action == PullRecycler.ACTION_PULL_TO_REFRESH) {
            page = 1;
        }
        BaseUser user = CustomApplication.getInstance().getUserModel();
        OkGo.<BaseResult<BasePageModel<ArrayList<BaseWrongBook>>>>post(BASE_URL+"findErrQuestionList.ajax")//请求方式和请求url
                .tag(this)//请求的 tag, 主要用于取消对应的请求
                .params("xlh", user.getXsXlh())//
                .params("currentPage", page++)//
                .params("maxRows", 10)//
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)  //缓存模式先使用缓存,然后使用网络数据
                .execute(new JsonCallback<BaseResult<BasePageModel<ArrayList<BaseWrongBook>>>>() {
                    @Override
                    public void onSuccess(Response<BaseResult<BasePageModel<ArrayList<BaseWrongBook>>>> response) {
//                        handleResponse(response);
                        String str = response.toString();
                        System.out.println(str);
                        if (action == PullRecycler.ACTION_PULL_TO_REFRESH) {
                            mDataList.clear();
                        }
                        if (response.body().result.getQueryList() == null || response.body().result.getQueryList().size() == 0) {
                            recycler.enableLoadMore(false);
                        } else {
                            recycler.enableLoadMore(true);
                            mDataList.addAll(response.body().result.getQueryList());
                            adapter.notifyDataSetChanged();
                        }
                        recycler.onRefreshCompleted();
                    }

                    @Override
                    public void onCacheSuccess(Response<BaseResult<BasePageModel<ArrayList<BaseWrongBook>>>> response) {
                        //一般来说,只需呀第一次初始化界面的时候需要使用缓存刷新界面,以后不需要,所以用一个变量标识
                        if (!isInitCache) {
                            //一般来说,缓存回调成功和网络回调成功做的事情是一样的,所以这里直接回调onSuccess
                            onSuccess(response);
                            isInitCache = true;
                        }
                    }

                    @Override
                    public void onError(Response<BaseResult<BasePageModel<ArrayList<BaseWrongBook>>>> response) {
//                        handleError(response);
                        recycler.onRefreshCompleted();
                    }
                });

    }

    class SampleViewHolder extends BaseViewHolder {

        ImageView iv_book_img;
        TextView tv_view;
//        TextView tv_date;
//        TextView tv_state;

        public SampleViewHolder(View itemView) {
            super(itemView);
            tv_view = (TextView) itemView.findViewById(R.id.tv_view);
//            tv_date = (TextView) itemView.findViewById(R.id.tv_date);
//            tv_state = (TextView) itemView.findViewById(R.id.tv_state);
//            iv_book_img = (ImageView) itemView.findViewById(R.id.iv_book_img);
        }

        @Override
        public void onBindViewHolder(int position) {
//            Glide.with(iv_book_img.getContext())
//                    .load(mDataList.get(position).getQuestion().getTitle())
//                    .centerCrop()
//                    .placeholder(R.color.app_primary_color)
//                    .crossFade()
//                    .into(iv_book_img);
//            CharSequence charsequence= Html.fromHtml(Html,new Html.ImageGetter(){
//
//                @override
//                public drawable getdrawable(string arg0) {
//                    drawable drawable=mainactivity.this.getresources().getdrawable(r.drawable.ic_launcher);
//                    //下面这句话不可缺少
//                    drawable.setbounds(0,0,drawable.getintrinsicwidth(),drawable.getintrinsicheight());
//                    return drawable;
//                }},null);
            String html = "<h1>this is h1</h1>"
                    + "<p>This text is normal</p>"
                    + "<img src='https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1293919120,3114443152&fm=26&gp=0.jpg' />";
            String str = mDataList.get(position).getQuestion().getTitle();
            CharSequence sp = Html.fromHtml(html, new Html.ImageGetter() {
                @Override
                public Drawable getDrawable(String source) {
                    InputStream is = null;
                    try {
                        is = (InputStream) new URL(source).getContent();
                        Drawable d = Drawable.createFromStream(is, "src");
                        d.setBounds(0, 0, d.getIntrinsicWidth(),
                                d.getIntrinsicHeight());
                        is.close();
                        return d;
                    } catch (Exception e) {
                        return null;
                    }
                }
            }, null);

            tv_view.setText(sp);
        }

        @Override
        public void onItemClick(View view, int position) {
            Toast.makeText(WrongBookListActivity.this, "dianji"+position, Toast.LENGTH_LONG).show();
        }

    }
}
